function image = fsb_threshold_cluster(image,clustparam,waitb)

% FSB : thresholds statistical maps with minimum cluster sizes
%
% EXAMPLE:
% image = fsb_threshold_cluster(image,5)
%
% INPUT:
% image:        3-D activation map
% Clustparam:   Minimum cluster size
% waitb:        Arbitrary input for displaying waitbar
%
% OUTPUT:
% image:        A thresholded 3-D activation map
%
% CALLED BY:
% FSB.m
%
% copyright Steffen Stoewer 02/08
%
% Copyright 2010 MPI for Biological Cybernetics
% Author: Steffen Stoewer
% License:GNU GPL, no express or implied warranties
%
%$ Revision 1.0
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Look for clusters and find total number of clusters
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

clusmap =  bwlabeln(image);
maxclus = max(clusmap(:));

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% In case you want to display a wait bar
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if nargin>2
    h = waitbar(0,'Thresholding clusters...');
    for x =1:maxclus;
        waitbar(x/maxclus);
        tempclus = (clusmap==x);
        tempclus2 = find(clusmap==x);
        if size(tempclus2,1)<clustparam;
            image (tempclus) = 0;
        end

    end
    close(h);
else
    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    % If you want it to run as fast as possible
    %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    for x =1:maxclus;
        tempclus = (clusmap==x);
        tempclus2 = find(clusmap==x);
        if size(tempclus2,1)<clustparam;
            image (tempclus) = 0;
        end
    end
end

end
